import tkinter 
from tkinter import filedialog
from tkinter.filedialog import askdirectory
import xlrd,os,re
#from tkinter import ttk

#img_path = filedialog.askopenfilename() 

class TKWIN():
    def __init__(self):
        self.win = tkinter.Tk()
        self.win.title("文件重命名工具0.05")
        self.file=""
        self.folder=""
        self.checkVar=tkinter.IntVar()
        self.head=0
        self.setupUI()
        
        
    def setupUI(self):
        self.frame1=tkinter.Frame(self.win,width=80,height=2)
        self.frame1.pack(pady=5)
        self.frame2=tkinter.Frame(self.win,width=80,height=2)
        self.frame2.pack(pady=5)
        self.frame3=tkinter.Frame(self.win,width=80,height=2)
        self.frame3.pack(pady=5)

        self.frame4=tkinter.Frame(self.win,width=80,height=2)
        self.frame4.pack(pady=5)
        self.frame41=tkinter.Frame(self.frame4,width=30,height=1)
        self.frame41.pack(pady=5,side="left")
        self.frame411=tkinter.Frame(self.frame41,width=30,height=1)
        self.frame411.pack(pady=5,side="left")
        self.frame412=tkinter.Frame(self.frame41,width=30,height=1)
        self.frame412.pack(pady=5)
        self.frame42=tkinter.Frame(self.frame4,width=20,height=1)
        self.frame42.pack(pady=5,side="right")

        self.bt1 = tkinter.Button(self.frame1, text ="选择excel文件", command = self.choosefile)
        self.bt1.pack(padx=5,side="left")
        self.text1=tkinter.Text(self.frame1,width=60,height=2)
        self.text1.pack(padx=5)

        self.bt2 = tkinter.Button(self.frame2, text ="选择音频文件夹", command = self.choosefolder)
        self.bt2.pack(padx=5,side="left")
        self.text2=tkinter.Text(self.frame2,width=60,height=2)
        self.text2.pack(padx=5)

        # self.combo1 = ttk.Combobox(self.win)
        # self.combo1['value'] = ('英式', '美式')
        # self.combo1.current(0)
        # self.combo1.pack()

        self.renamebt = tkinter.Button(self.frame3, text ="重命名", font=('微软雅黑',10,'bold'),command = self.renameFiles)
        self.renamebt.pack(padx=10,side="left")

        # self.renamebt = tkinter.Button(self.frame3, text ="美式重命名", command = self.renameb)
        # self.renamebt.pack(padx=40,side="right")

        self.text3=tkinter.Text(self.frame3,width=60,height=2)
        self.text3.pack()

        tkinter.Label(self.frame411,text="原名列").pack(padx=5,side="left")
        self.entry1=tkinter.Entry(self.frame411,width=5)
        self.entry1.insert("0","2")
        self.entry1.pack(padx=5)

        tkinter.Label(self.frame412,text="新名列").pack(padx=5,side="left")
        self.entry2=tkinter.Entry(self.frame412,width=5)
        self.entry2.insert("0","1")
        self.entry2.pack(padx=5)

        self.checkbt=tkinter.Checkbutton(self.frame42,text="首行标题",variable=self.checkVar,command=self.checkhead)
        #self.checkbt.select()
        self.checkbt.pack(padx=5)

    def checkhead(self):
        self.head=self.checkVar.get()
        print(f"首行标题:{type(self.head)},{self.head}")

    def choosefile(self):
        self.file= filedialog.askopenfilename() 
        self.text1.delete("0.0",tkinter.END)
        self.text1.insert("0.0",self.file)

    def choosefolder(self):
        self.folder=askdirectory()
        self.text2.delete("0.0",tkinter.END)
        self.text2.insert("0.0",self.folder)

    def reade(self):
        #print(self.file)
        book=xlrd.open_workbook(self.file)
        lines=[]
        sheet=book.sheet_by_index(0)
        rown=sheet.nrows
        for i in range(rown):
            lines.append(sheet.row_values(i))
        return lines

    def renameFiles(self,typea="英式"):
        self.text3.delete("0.0",tkinter.END)
        if not self.file:
            self.text3.insert("0.0","请先选择命名映射excel文件")
            return
        if not self.folder:
            self.text3.insert("0.0","请先选择音频文件夹")
            return
        
        lines=self.reade()
        col1=int(self.entry1.get())-1
        col2=int(self.entry2.get())-1

        if self.head:
            lines=lines[1:]
        namedic={}
        for i,line in enumerate(lines):
            aname=line[col1]
            if type(aname) == float or type(aname) == int:
                aname=str(int(aname))
            else:
                aname=str(aname).strip()
            namedic[aname]=str(line[col2])
        #print("namedic:")
        print(namedic)
        fails=[]
        files=os.listdir(self.folder)
        print(files)
        for f in files:
            f1=self.folder+"/"+f 
            fs=f.split(".")
            if len(fs)>2:
                continue 
            fb,af=fs

            if fb in namedic:
                f2=f"{self.folder}/{namedic[fb]}.{af}"
                try:
                    os.rename(f1,f2)
                except Exception as e:
                    print(f"{f1} rename to {f2} error:{e}")
                    fails.append(f)
            elif re.search("^[0-9_]+$",f):
                print(f"{f} not found in excel!skipped")
                fails.append(f)
        self.text3.delete("0.0",tkinter.END)
        if fails:
            fails=",".join(fails)
            self.text3.insert("0.0",f"部分重命名失败:{fails}")
        else:
            self.text3.insert("0.0",f"{typea}重命名成功！")
        
    def renamea(self):
        self.renameFiles("英式")

    def renameb(self):
        self.renameFiles("美式")



# 进入消息循环
tkwin=TKWIN()
tkwin.win.mainloop()